# NarutoCN Image Getter
# Get cartoon pictures from www.narutocn.net automatically
# chuanshenglu@gmail.com
# usage:
#         perl getimg.pl [base_url] [start_series] [end_series] [output zip:1/0] [verbose:1/0]
#  e.g.  perl getimg.pl http://comic-zj.narutocn.net/comic/bleach 251 300
#!/usr/bin/perl -w

use LWP::Simple;
use LWP::UserAgent;
use File::Spec;

my ( $base_url, $start_series, $end_series, $if_zip, $if_verbose ) = @ARGV;

#defined($base_url) || ($base_url="http://tu.jumpcn.com.cn/586/%E7%AC%AC30%E5%8D%B7");
my $postfix="png";
my $url="$base_url/$series/$n.png";
my $root=File::Spec->rel2abs("./");
my $progress_len=0;

( defined( $start_series) && defined( $end_series) ) || die "Must specify the start, end series\n";
defined($MAX_SERIES) || ($MAX_SERIES=400);
defined( $if_zip) || ($if_zip=0);

chdir $root;
my $errlog="error_log.txt";                   #log error messages in error log;
!(-d "$errlog") || `rm -f $errlog`;
open ERRLOG,"+>$errlog";

#foreach( my $series=$start_series; $series<=$end_series;++$series)
#for( my $series=$series_start; $series<=$series_end; ++$series)
foreach( $start_series..$end_series)
{
    # the series befor 430 (not included) is JPG format;
    $postfix="jpg";#get_img_postfix("$base_url/%E7%AC%AC$s%E5%8D%B7");
    my $series=$_;
#    print "$series\n\n\n\n";
#    die "";
    my $dir="$root/$series";
    print "Postfix $postfix\n";
    #make directory for each series;
    print "mkdir $dir\n";
    mkdir $dir;
    print "chdir $dir\n";
    chdir $dir;
    my $dir_error=0;

    #Retrieve pictures from server;
    foreach( 1..210)
    {
#        my $fname=&make_file_name( $_ ).".$postfix";
        my $fname=$_.".$postfix";
        $url="$base_url/%E7%AC%AC$series%E5%8D%B7/$fname";
#        print "$url\n";
        print "Get: $url\n";
        my $ua = new LWP::UserAgent;
        my $response = $ua->get( $url, 
                                 ':content_file' => "$fname" );

        #if got abnormal response jump to the next loop
        if( !($response->filename eq $fname) || $response->is_error)
        {
            ($n!=1) || ($dir_error=1);      #if only one was downloaded, error occurs!!!
            `rm -rf $fname` unless !(-e $fname);
#            last;
        }else{
            print "#";
            flush STDOUT;
        }
    }
    chdir $root;
    if($dir_error==1){        #If error, delete the directory;
        `rm -rf $dir`;
        print ERRLOG "Fail to download $url\nDelete incompleted directory $root/$s";
        next;
    }
    do{
        print "Compress dir $series into $series.zip\n";
        `perl archdir.pl $root`;
    }unless ($if_zip==0);
}
